<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/9/9
 * Time: 0:51
 */
namespace app\teacher\model;

use app\exam\model\ExamScheduleManager;
use think\Config;

class TeacherExamManager extends ExamScheduleManager{
    const EXSIT_EXAM = "已存在考试";
    const OVER_EXAM = "不能更改已考完的场次";
    const SAME_EXAM = "无法更改同一个场次";
    const MISS_EXAM = "考试场次不存在";

    const DB_NAME = "exam_registration";

    public function __construct()
    {
        parent::__construct();
    }

    /*
     * 发布考试
     */
    public function createTeacherExam($examInfo){
        return $this->createExamScheduleByCustom($examInfo);
    }

    public function deleteTeacherExam($id){
        return $this->deleteExamScheduleById($id);
    }
    /*
     * 更新考试内容
     */
    public function updateTeacherExam($id,$info){

        //判断修改的原来地址是否存在，判断状态是否为考完
        $result = $this->getExamScheduleByCustom(array("id"=>$id));

        if($result==NULL){
            echoJson(0, self::MISS_EXAM);
        }else if($result["status"] == parent::OUT_EXAM){
            echoJson(0,self::OVER_EXAM);
        }

        //判断修改的场次是否占用
        if($info["id"] != null){
            if($id != $info["id"]){
                $exam = $this->getExamScheduleByCustom(array("id"=>$info["id"]));

                if($exam){
                    echoJson(0,self::EXSIT_EXAM);
                }
            }
        }

        return $this->updateExamScheduleByCustom(array("id"=>$id),$info);
    }

    public function getTeacherExamListCount($status=parent::OUT_EXAM){
        return count($this->getExamScheduleAllByCustom(array("status"=>$status),null));
    }

    public function getTeacherExamList($examinfo,$page=null){
        //$sql = "select * from ".self::DB_NAME." where ";
        return $this->getExamScheduleAllByCustom($examinfo,null,$page);
    }

    public function getTeacherExamDetail($id){
        $sql = "select A.student_id,C.name,C.college,C.class,B.date,B.place,A.score from exam_registration 
AS A INNER join exam_schedule AS B on A.exam_id=B.id INNER join student AS C on A.student_id=C.id where A.exam_id='$id'";
        $result = $this->selectSQLAllbyCustom(self::DB_NAME,null,$sql);
        return $result;
    }

    public function downloadTeacherExam($id){
        $sql = "select A.student_id,C.name,C.college,C.class,B.date,B.place,A.score,B.status from exam_registration 
AS A INNER join exam_schedule AS B on A.exam_id=B.id INNER join student AS C on A.student_id=C.id where A.exam_id='$id'";

        $result = $this->selectSQLAllbyCustom(self::DB_NAME,null,$sql);

        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator("作者")
            ->setLastModifiedBy("更改者")
            ->setTitle("计算机文化")
            ->setSubject("考场下载")
            ->setDescription("文档的描述信息")
            ->setKeywords("设置文档关键词")
            ->setCategory("设置文档的分类");

        if($result[0]["status"] == parent::UNACCEPT_EXAM){
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '场次')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '学号')
                ->setCellValue('D1', '学院')
                ->setCellValue('E1', '班级')
                ->setCellValue('F1', '签字');

            foreach ($result as $key=>$value){
                //var_dump($key);
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue("A".($key+2), $id)
                    ->setCellValue("B".($key+2), $value["name"])
                    ->setCellValue("C".($key+2), $value["student_id"])
                    ->setCellValue("D".($key+2), $value["college"])
                    ->setCellValue("E".($key+2), $value["class"]);
            }

            $objPHPExcel->getActiveSheet()->setTitle('第一个sheet');
            $objPHPExcel->setActiveSheetIndex(0);
        }else if($result[0]["status"] == parent::OUT_EXAM){
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '场次')
                ->setCellValue('B1', '姓名')
                ->setCellValue('C1', '学号')
                ->setCellValue('D1', '学院')
                ->setCellValue('E1', '班级')
                ->setCellValue('F1', '成绩');

            foreach ($result as $key=>$value){
                //var_dump($key);
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue("A".($key+2), $id)
                    ->setCellValue("B".($key+2), $value["name"])
                    ->setCellValue("C".($key+2), $value["student_id"])
                    ->setCellValue("D".($key+2), $value["college"])
                    ->setCellValue("E".($key+2), $value["class"])
                    ->setCellValue("F".($key+2), $value["score"]);
            }

            $objPHPExcel->getActiveSheet()->setTitle('第一个sheet');
            $objPHPExcel->setActiveSheetIndex(0);
        }else{
            echoJson(0, "下载错误");
        }


// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        //$objWriter->save( 'export.xlsx');
        $file_name = "exam";
        $savePath = config('upload_path');
        //if($isDown){   //网页下载
//        header('pragma:public');
//        header("Content-Disposition:attachment;filename=$fileName.xls");
//        $objWriter->save('php://output');
        //exit;
        //}

        if(!file_exists(config('upload_path').'/excel')){
            mkdir(config('upload_path').'/excel');
            chmod(config('upload_path').'/excel',0777);
        }
        (new \PHPExcel_Writer_Excel2007($objPHPExcel))->save(config('upload_path').'/excel/exam.xlsx');

//        $contents = file_get_contents(config('upload_path').'/excel/checklist.xls');
//        $file_size = filesize(config('upload_path').'/excel/checklist.xls');
//        header("Content-type: application/octet-stream;charset=utf-8");
//        header("Accept-Ranges: bytes");
//        header("Accept-Length: $file_size");
//        header("Content-Disposition: attachment; filename=".$file_name);
//        exit($contents);

        return config('path').$savePath."/excel/".$file_name.'.xlsx';
        //return $result;
    }

    public function updateStudentScore($examinfo){
        $score["score"] = $examinfo["score"];
        $score["status"] = 1;
        unset($examinfo["score"]);
        //var_dump($examinfo);
        return $this->updateSQLbyCustom(self::DB_NAME,$examinfo,$score);
    }
}